﻿package com.badibadi.logic;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.ExifInterface;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.ab.bitmap.AbImageDownloader;
import com.ab.util.AbImageUtil;
import com.badibadi.activity.BaseActivity;
import com.badibadi.activity.UpPictures3Activity;
import com.badibadi.infos.ImageAttribute;
import com.badibadi.logic.ImgsAdapter.OnImgsGridViewScrollListener;
import com.badibadi.logic.ImgsAdapter.OnItemClickClass;
import com.badibadi.uniclubber.R;
import com.lidroid.xutils.BitmapUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

/**
 * 上传图片的activity
 * 
 * @author Administrator selected_image_layout return_btn selected_image_layout
 *         up_button
 * 
 */
public class ImgsActivity extends BaseActivity {

	protected static final String TAG = "ImgsActivity";
	Bundle bundle;
	Message message;
	FileTraversal fileTraversal;
	GridView imgGridView;
	ImgsAdapter imgsAdapter;
	LinearLayout select_layout;
	Util util;
	RelativeLayout relativeLayout2;
	HashMap<Integer, ImageView> hashImage;
	Button choise_button;
	ArrayList<String> filelist;
	String panduan;
	String club = null, no_dou = null, photoid = null, activity_id = null;
	BitmapUtils bitmapUtils;
	boolean isRun = true;// 清理图片缓存的

	private List<String> list = null;

	private DisplayImageOptions options;
	private AbImageDownloader mAbImageDownloader = null;
	Thread t;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		goToTheTitle();
		setContentView(R.layout.img_photogrally);
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.ic_stub)
				.showImageForEmptyUri(R.drawable.noimage)
				.showImageOnFail(R.drawable.noimage).cacheInMemory()
				.bitmapConfig(Bitmap.Config.RGB_565)
				// .displayer(new FadeInBitmapDisplayer(300)) // 渐变
				.displayer(new RoundedBitmapDisplayer(0)).build();
		mAbImageDownloader = new AbImageDownloader(ImgsActivity.this);
		mAbImageDownloader.setErrorImage(R.drawable.noimage);
		mAbImageDownloader.setLoadingImage(R.drawable.ic_stub);
		mAbImageDownloader.setType(AbImageUtil.ORIGINALIMG);

		panduan = getIntent().getStringExtra("panduan");
		club = getIntent().getStringExtra("club");
		no_dou = getIntent().getStringExtra("no_dou");
		photoid = getIntent().getStringExtra("photoid");
		activity_id = getIntent().getStringExtra("activity_id");
		imgGridView = (GridView) findViewById(R.id.gridView1);
		bundle = getIntent().getExtras();
		fileTraversal = bundle.getParcelable("data");
		list = new ArrayList(fileTraversal.filecontent);
		Collections.reverse(list);
		// 相測最新的在最上面
		imgsAdapter = new ImgsAdapter(this, list, onItemClickClass);
		// imgsAdapter = new ImgsAdapter(this, fileTraversal.filecontent,
		// onItemClickClass);
		// 自己写的
		imgsAdapter
				.setOnImgsGridViewScrollListener(new OnImgsGridViewScrollListener() {

					@Override
					public void ImgsGridView(ImageView iv, String path) {
						// TODO Auto-generated method stub
						// new BitmapHelp().displayImage(ImgsActivity.this, iv,
						// path, imgGridView);
						try {
							// ImageLoader.getInstance().displayImage(
							// "file://" + path, iv, options);
							//

							ImageLoader.getInstance().displayImage(
									"file://" + path, iv, options);
						} catch (Exception e) {
							// TODO: handle exception
						}

					}
				});
		imgGridView.setAdapter(imgsAdapter);
		select_layout = (LinearLayout) findViewById(R.id.selected_image_layout);
		relativeLayout2 = (RelativeLayout) findViewById(R.id.relativeLayout2);
		choise_button = (Button) findViewById(R.id.up_button);
		hashImage = new HashMap<Integer, ImageView>();
		filelist = new ArrayList<String>();
		// imgGridView.setOnItemClickListener(this);
		util = new Util(this);

		// bitmapUtils=BitmapHelp.getBitmapUtils(this);
		this.findViewById(R.id.up_button).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						sendfiles();
					}
				});
	}

	class BottomImgIcon implements OnItemClickListener {

		int index;

		public BottomImgIcon(int index) {
			this.index = index;
		}

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {

		}
	}

	@SuppressLint("NewApi")
	public ImageView iconImage(String filepath, int index, CheckBox checkBox)
			throws FileNotFoundException {
		LinearLayout.LayoutParams params = new LayoutParams(
				relativeLayout2.getMeasuredHeight() - 10,
				relativeLayout2.getMeasuredHeight() - 10);
		ImageView imageView = new ImageView(this);
		imageView.setLayoutParams(params);
		imageView.setBackgroundResource(R.drawable.imgbg);
		imageView.setPadding(0, 5, 0, 5);
		float alpha = 100;
		imageView.setAlpha(alpha);
		util.imgExcute(imageView, imgCallBack, filepath);
		imageView.setOnClickListener(new ImgOnclick(filepath, checkBox));
		return imageView;
	}

	ImgCallBack imgCallBack = new ImgCallBack() {
		@Override
		public void resultImgCall(ImageView imageView, Bitmap bitmap,
				String path2) {

			try {
				ImageLoader.getInstance().displayImage("file://" + path2,
						imageView, options);
				//
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	};

	class ImgOnclick implements OnClickListener {
		String filepath;
		CheckBox checkBox;

		public ImgOnclick(String filepath, CheckBox checkBox) {
			this.filepath = filepath;
			this.checkBox = checkBox;
		}

		@Override
		public void onClick(View arg0) {
			checkBox.setChecked(false);
			select_layout.removeView(arg0);
			String aa = String.format(
					getResources().getString(R.string.wx2_27), ""
							+ select_layout.getChildCount());
			choise_button.setText(aa);
			filelist.remove(filepath);
		}
	}

	ImgsAdapter.OnItemClickClass onItemClickClass = new OnItemClickClass() {
		@Override
		public void OnItemClick(View v, int Position, CheckBox checkBox) {
			// String filapath = fileTraversal.filecontent.get(Position);
			String filapath = list.get(Position);
			if (checkBox.isChecked()) {
				checkBox.setChecked(false);
				if (imgsAdapter.getTitleMap().containsKey(Position) == true) {
					imgsAdapter.getTitleMap().remove(Position);
				}

				select_layout.removeView(hashImage.get(Position));
				filelist.remove(filapath);
				String aa = String.format(
						getResources().getString(R.string.wx2_27), ""
								+ select_layout.getChildCount());

				choise_button.setText(aa);
			} else {
				try {
					checkBox.setChecked(true);
					//
					imgsAdapter.getTitleMap().put(Position, filapath);
					ImageView imageView = iconImage(filapath, Position,
							checkBox);
					if (imageView != null) {
						hashImage.put(Position, imageView);
						filelist.add(filapath);
						select_layout.addView(imageView);

						String aa = String.format(
								getResources().getString(R.string.wx2_27), ""
										+ select_layout.getChildCount());
						choise_button.setText(aa);
					}
				} catch (FileNotFoundException e) {

				}
			}
		}
	};

	public void tobreak(View view) {
		// startActivity(new Intent(ImgsActivity.this,
		// ImgFileListActivity.class));
		// Intent intent = new Intent(ImgsActivity.this,
		// ImgFileListActivity.class);
		// intent.putExtra("panduan", panduan);
		// startActivity(intent);
		finish();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 5 && resultCode == 5) {
			ArrayList<String> filelist = data.getStringArrayListExtra("files");
			ImageAttribute attribute = (ImageAttribute) data
					.getSerializableExtra("img_info");
			Intent intent = new Intent();
			intent.putExtra("files", filelist);
			if (attribute != null) {
				intent.putExtra("img_info", attribute);
			}

			setResult(5, intent);
			finish();
		}
	}


	/**
	 * FIXME 亲只需要在这个方法把选中的文档目录已list的形式传过去即可(修改后需用handler传入指定界面更新,what=3000)
	 * 
	 * @param view
	 */
	public void sendfiles() {
		if (filelist.size() != 0) {
			if (filelist.size() <= 9) {
				if (panduan.equals("set")) {
					Intent intent = new Intent(this, UpPictures3Activity.class);
					Bundle bundle = new Bundle();
					bundle.putStringArrayList("files", filelist);
					bundle.putString("pan", "douhao");
					if (club != null) {
						bundle.putString("club", club);
					}
					if (no_dou != null) {
						bundle.putString("no_dou", no_dou);
					}
					if (photoid != null) {
						intent.putExtra("photoid", photoid);
					}
					if (activity_id != null) {
						intent.putExtra("activity_id", activity_id);
					}
					intent.putExtras(bundle);
					startActivityForResult(intent, 5);
					// startActivity(intent);
					// this.finish();
				} else if (panduan.equals("no_set")) {
					// for (int i = 0; i < filelist.size(); i++) {
					// // ("上传的图片是" + filelist.get(i));
					//
					// }
					Intent intent = new Intent();
					intent.putExtra("files", filelist);
					setResult(5, intent);
					finish();
				} else {
					Toast.makeText(getApplicationContext(),
							getResources().getString(R.string.wx2_12), 0)
							.show();
				}
			} else {
				Toast.makeText(getApplicationContext(),
						getResources().getString(R.string.wx2_10), 0).show();
			}
		} else {
			Toast.makeText(getApplicationContext(),
					getResources().getString(R.string.wx2_11), 0).show();
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		try {
			isRun = false;
			// 改
			ImageLoader.getInstance().clearDiscCache();
			ImageLoader.getInstance().clearMemoryCache();
		} catch (Exception e) {
			// TODO: handle exception
		}
		super.onDestroy();
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		try {
			isRun = true;
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		try {
			isRun = false;
			// 改
			ImageLoader.getInstance().clearDiscCache();
			ImageLoader.getInstance().clearMemoryCache();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
